package com.kingsoft.miot.bridge.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.kingsoft.miot.bridge.dao.AccountRecordDao;
import com.kingsoft.miot.bridge.pojo.ServiceAuth;
import com.kingsoft.miot.bridge.pojo.SignAndVerify;
import com.kingsoft.miot.bridge.pojo.account.AccountRecord;
import com.kingsoft.miot.bridge.pojo.account.AccountUris;
import com.kingsoft.miot.bridge.service.AccountService;
import com.kingsoft.miot.bridge.service.BaseService;
import com.kingsoft.miot.bridge.utils.HttpUtils;

/**
 * 账号ID服务
 * 
 * @author HUJIANQING
 *
 */
@Service
@ConditionalOnBean(value = { ServiceAuth.class, AccountUris.class })
public class AccountServiceImpl extends BaseServiceImpl implements AccountService, BaseService {

	private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

	// 服务商提供参数
	@Autowired
	private ServiceAuth serviceAuth;

	// 账户Uri
	@Autowired
	private AccountUris accountUris;

	@Autowired
	private AccountRecordDao accountRecordDao;

	@Transactional
	@Override
	public void addAccountRecord(AccountRecord accountRecord) {
		accountRecordDao.insertOne(accountRecord);
	}

	/**
	 * echo测试
	 */
	@Override
	public String echoTest(String echoStr) {
		if (StringUtils.isBlank(echoStr)) {
			echoStr = "it is echo string";
		}
		String result = "";
		String method = "POST";
		String url = serviceAuth.getServiceUrl() + accountUris.getEchoUri();
		JSONObject dataMap = new JSONObject();
		try {
			dataMap.put("echo", echoStr);
			String value = dataMap.toJSONString();
			// 时间戳
			String nonceStr = System.currentTimeMillis() + "";
			List<NameValuePair> params = new ArrayList<>();
			// 填充groupId 和 AuthUnitId
			String groupId = serviceAuth.getGroupId();
			params.add(new BasicNameValuePair("_groupId", groupId));
			params.add(new BasicNameValuePair("_nonce", nonceStr));
			params.add(new BasicNameValuePair("_data", value));
			// ECDSA 离线验证
			SignAndVerify signAndVerify = verify(method, accountUris.getEchoUri(), value, nonceStr,
					serviceAuth.getPublicKey(), serviceAuth.getPrivateKey());
			// 待参考
//			if (!signAndVerify.isVerify()) {
//				LOGGER.error("离线验证失败。");
//				return null;
//			}
			params.add(new BasicNameValuePair("_signature", signAndVerify.getSign()));
			result = HttpUtils.sendPost(url, params);
		} catch (Exception e) {
			LOGGER.error("测试出现未知异常。");
		}
		return result;
	}

	/**
	 * 生产一个controlUnitID 通过groupid 和 authid 也就是小账号
	 * 
	 * @return 返回control unitID
	 */
	@Override
	public String controlUnit(String authid) {
		if (StringUtils.isBlank(authid)) {
			throw new RuntimeException("authid 不能为空");
		}
		String result = "";
		String method = "POST";
		String url = serviceAuth.getServiceUrl() + accountUris.getControlunitUri();
		// 1. 获取control unit
		try {
			// _data
			JSONObject dataMap = new JSONObject();
			String value = dataMap.toJSONString();
			// 时间戳
			String nonceStr = System.currentTimeMillis() + "";
			List<NameValuePair> params = new ArrayList<>();
			// 填充groupId 和 AuthUnitId
			params.add(new BasicNameValuePair("_nonce", nonceStr));
			params.add(new BasicNameValuePair("_groupId", serviceAuth.getGroupId()));
			params.add(new BasicNameValuePair("_authUnitId", authid));
			params.add(new BasicNameValuePair("_data", value));
//			System.out.println(params);
			// ECDSA 离线验证
			SignAndVerify signAndVerify = verify(method, accountUris.getControlunitUri(), value, nonceStr,
					serviceAuth.getPublicKey(), serviceAuth.getPrivateKey());
			// 待参考
//			if (!signAndVerify.isVerify()) {
//				LOGGER.error("离线验证失败。");
//				return null;
//			}
			params.add(new BasicNameValuePair("_signature", signAndVerify.getSign()));
			result = HttpUtils.sendPost(url, params);
		} catch (Exception e) {
			LOGGER.error("测试出现未知异常。");
		}
		// 返回结果不为空
		String controlUnitId = null;
		if (!StringUtils.isBlank(result)) {
			// 2. 插入一条账户记录
			AccountRecord accountRecord = new AccountRecord();
			accountRecord.setAuth_unit_id(authid);
			JSONObject jsonObject = new JSONObject();
			Map<String, Object> map = jsonObject.parseObject(result, Map.class);
			Object object = map.get("data");
			Map<String, Object> map2 = jsonObject.parseObject(object.toString(), Map.class);
			Object obj = map2.get("controlUnitId");
			if (obj == null) {
				return null;
			}
			controlUnitId = obj.toString();
			accountRecord.setControl_unit_id(Long.valueOf(controlUnitId));
			Date date = new Date();
			accountRecord.setAccount_record_create_time(date);
			accountRecord.setAccount_record_update_time(date);
			// 添加新记录
			addAccountRecord(accountRecord);
		}
		// 返回
		return controlUnitId;
	}

	@Override
	public String bindPhoneSms(String phone) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String bindPhone(String phoneTicket) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String bindKeySms() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String controlUnits(String cursor, int limit) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String disableReset(long controlUnitId, String did) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDisableReset(long controlUnitId, String did) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String rpc(long controlUnitId, String did, String rpcName, String params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String setMgr(long userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delMgr(long userId) {
		// TODO Auto-generated method stub
		return null;
	}

}
